# -*- coding: utf-8 -*-
# @Author  : caiweichao
# @explain : 封装http请求类


import allure
import requests

from Commons.util.json_util import JsonUtil
from Commons.util.logs import Log


class HttpRequset:

    @allure.step("发起请求")
    def __init__(self, method: str, url: str, data=None, cookies=None, headers=None):
        """
        请求的基础类
        :param method: 请求方式
        :param url: 请求的url
        :param data: 请求的参数
        :param cookies: 请求中带的cookie
        :param headers: 请求头
        """
        try:
            if method.upper() == "GET":
                self._res = requests.session().get(url=url, params=data, headers=headers, cookies=cookies)
            elif method.upper() == "POST":
                if isinstance(data, str):
                    self._res = requests.session().post(url=url, json=JsonUtil.load_json(data), headers=headers,
                                                        cookies=cookies)
                else:
                    self._res = requests.session().post(url=url, json=data, headers=headers,
                                                        cookies=cookies)
            else:
                Log.error(f"请求类未添加对应请求方式{method}")
            with allure.step("请求日志"):
                Log.info("-----------------------------------------------")
                Log.info("请求信息:")
                Log.info(f"request_url:{self._res.request.url}")
                Log.info(f"request_headers:{self._res.request.headers}")
                Log.info(f"request_body:{self._res.request.body}")
                Log.info(f"request_cookies:{self._res.cookies}")
                Log.info("响应信息:")
                Log.info(f"response_headers:{self._res.headers}")
                Log.info(f"response_body:{self._res.text}")
                Log.info("-----------------------------------------------")
        except Exception:
            Log.error(Exception)
            raise Exception("请求异常请检查")

    # 获取请求的cookies
    def get_cookies(self):
        return self._res.cookies

    # 获取接口返回的json对象
    def get_json(self):
        return self._res.json()

    # 获取接口返回的json对象
    def getText(self):
        return self._res.text

    # 获取接口的返回的code
    def get_code(self):
        return self._res.status_code

    # 获取接口的全部响应时间
    def get_response_time(self):
        return self._res.elapsed.total_seconds()

    def assert_response(self, rule):
        return JsonUtil.jsonToOneValue(jsonObj=self.get_json(), rule=rule)


if __name__ == '__main__':
    pass
